package com.java.flowable.myflowable.controller;

import com.java.flowable.myflowable.domain.vo.FlowQueryVo;
import com.java.flowable.myflowable.tool.api.R;
import com.java.flowable.myflowable.domain.dto.FlowTaskDto;
import com.java.flowable.myflowable.domain.vo.FlowTaskVo;
import com.java.flowable.myflowable.service.IFlowTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


@Slf4j
@Api(tags = "工作流流程任务管理")
@RestController
@RequestMapping("/flowable/task")
public class FlowTaskController {

    @Autowired
    private IFlowTaskService flowTaskService;


    @ApiOperation(value = "获取待办列表", response = FlowTaskDto.class)
    @GetMapping(value = "/todoList")
    public R todoList(FlowQueryVo queryVo) {
        return R.data(flowTaskService.todoList(queryVo));
    }

    @ApiOperation(value = "获取已办任务", response = FlowTaskDto.class)
    @GetMapping(value = "/finishedList")
    public R finishedList(FlowQueryVo queryVo) {
        return R.data(flowTaskService.finishedList(queryVo));
    }

    @ApiOperation(value = "审批任务")
    @PostMapping(value = "/complete")
    public R complete(@RequestBody FlowTaskVo flowTaskVo) {
        return R.status(flowTaskService.complete(flowTaskVo));
    }

    /**
     * 生成流程图
     *
     * @param processId 任务ID
     */
    @GetMapping("/diagram/{processId}")
    public void genProcessDiagram(HttpServletResponse response,
                                  @PathVariable("processId") String processId) {
        InputStream inputStream = flowTaskService.diagram(processId);
        OutputStream os = null;
        BufferedImage image = null;
        try {
            image = ImageIO.read(inputStream);
            response.setContentType("image/png");
            os = response.getOutputStream();
            if (image != null) {
                ImageIO.write(image, "png", os);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
